#include <ucontext.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "list.h"
#include "thread.h"
#include "signal.h"
#include <valgrind/valgrind.h>

int sigaction_t(int signum,void (*sig_hdlr) (int)){
  struct thread_elt * current_thread = cursor_ready;

  struct signal_elt * signal = malloc(sizeof(struct signal_elt));
  signal->id_sig = signum;
  signal->sig_handler = sig_hdlr;
  signal->parent_thread = cursor_ready;
  signal->next_rcvd_sig = NULL;
  signal->next_thread_sig = NULL;

  add_signal(signal, &(current_thread->sig));

  return 1;
}


int kill_t(struct thread_elt * thread,int sig_num){

  if(thread == NULL || thread->sig == NULL)
    return -1;

  struct signal_elt * tmp = thread->sig;
  while(tmp!=NULL && tmp->id_sig !=sig_num)
    tmp = tmp->next_thread_sig;

  if(tmp == NULL)
    return -1;
  
  if(sig_list == NULL)
    sig_list = tmp;
  else {
    struct signal_elt * tmp2 = sig_list;
    while(tmp2->next_rcvd_sig != NULL) {
      tmp2 = tmp2->next_rcvd_sig;
    }
    tmp2->next_rcvd_sig = tmp;
  }

  thread->sig->id_sig = sig_num;

  //add_list(thread

  return 1;
}






void add_signal(struct signal_elt *e, struct signal_elt **list) {

  if(*list == NULL) {
    *list = e;
  }
  else {
    struct signal_elt *tmp = *list;
    while(tmp->next_thread_sig != NULL) {
      tmp = tmp->next_thread_sig;
    }
    tmp->next_thread_sig = e;
  }

}
